package com.eralink.unionuhfreader.ui;


import android.content.Intent;
import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;


import androidx.annotation.Nullable;


import com.eralink.unionuhfreader.MyApplication;
import com.eralink.unionuhfreader.R;
import com.eralink.unionuhfreader.base.BaseActivity;
import com.eralink.unionuhfreader.bean.Auth;
import com.eralink.unionuhfreader.bean.CashierDO;
import com.eralink.unionuhfreader.http.Api;
import com.eralink.unionuhfreader.http.JsonCallBack;
import com.eralink.unionuhfreader.http.Result;
import com.eralink.unionuhfreader.util.ApkUils;
import com.eralink.unionuhfreader.util.SharedPreferencesUtil;
import com.eralink.unionuhfreader.util.ToastUtil;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

public class LoginActivity extends BaseActivity {
    Button btnLogin;
    EditText etaccount, etpassword;
    TextView title, tx_sn;
    RadioGroup rg_model;
    RadioButton rdb_manu, rdb_auto;
    int casherModel = 0;//收银模式
    private Button btn_settings;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        checkPerssion();
        initview();
        getdeviceinfo(0);
        ApkUils apkUils=new ApkUils(this);
        apkUils.checkAPP();
    }
    private void checkPerssion() {
        AndPermission.with(this)
                .permission(Permission.Group.STORAGE, Permission.Group.CAMERA, Permission.Group.PHONE)
                // 准备方法，和 okhttp 的拦截器一样，在请求权限之前先运行改方法，已经拥有权限不会触发该方法
                .rationale((context, permissions, executor) -> {
                    // 此处可以选择显示提示弹窗
                    executor.execute();
                })
                // 用户给权限了
                .onGranted(permissions -> ToastUtil.showToast("授权成功"))
                // 用户拒绝权限，包括不再显示权限弹窗也在此列
                .onDenied(permissions -> {
                    // 判断用户是不是不再显示权限弹窗了，若不再显示的话进入权限设置页
                    if (AndPermission.hasAlwaysDeniedPermission(LoginActivity.this, permissions)) {
                        // 打开权限设置页
                        ToastUtil.showToast("请授予应用权限");
                        return;
                    }
                    ToastUtil.showToast("用户拒绝权限");
                    finish();
                })
                .start();
    }
    private void getdeviceinfo(int i) {
        Api.getCachier(new JsonCallBack<Result<CashierDO>>() {
            @Override
            public void onSuccess(Response<Result<CashierDO>> response) {
                Result<CashierDO> result = response.body();
                if (result.isSucess() && result.getData() != null) {
                    MyApplication.cashierDO = result.getData();
                    title.setText(MyApplication.cashierDO.getName());
                    try {
                        casherModel=Integer.valueOf(MyApplication.cashierDO.getCashType());
                        if (casherModel==1){
                            rdb_auto.setChecked(true);
                            rdb_manu.setChecked(false);
                        }else{
                            rdb_auto.setChecked(false);
                            rdb_manu.setChecked(true);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    if (i == 1) {
                        if (casherModel == 1) {
                            //自助收银
                            startActivity(new Intent(LoginActivity.this, WelcomeActivity.class));
                        } else {
                            //人工收银
                            startActivity(new Intent(LoginActivity.this, ManualCasherActivity.class));
                        }
                        finish();
                    }
                } else {
                    title.setText(getString(R.string.cashiername));
                    showToast(result.getMsg());
                }
            }
        });
    }

    private void initview() {
        btnLogin = findViewById(R.id.btn_login);
        etaccount = findViewById(R.id.et_account);
        etpassword = findViewById(R.id.et_password);
        title = findViewById(R.id.title);
        tx_sn = findViewById(R.id.tx_sn);
        tx_sn.setText("序列号：" + MyApplication.getSn());
        rg_model = findViewById(R.id.rg_model);
        rdb_manu = findViewById(R.id.rdb_manu);
        rdb_auto = findViewById(R.id.rdb_auto);
        btn_settings=findViewById(R.id.btn_settings);
      String username= (String) SharedPreferencesUtil.getData(LoginActivity.this,"username","");
        String password= (String) SharedPreferencesUtil.getData(LoginActivity.this,"password","");
        etaccount.setText(username);
        etpassword.setText(password);
        btn_settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this,SettingActivity.class));
            }
        });
        rg_model.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case 1:
                        casherModel = 0;
                        break;
                    case 2:
                        casherModel = 1;
                        break;
                    case R.id.rdb_manu:
                        casherModel = 0;
                        break;
                    case R.id.rdb_auto:
                        casherModel = 1;
                        break;
                }

            }
        });
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (etaccount.getText().toString().equals("")) {
                    showToast(getString(R.string.account_not_null));
                    return;
                }
                if (etpassword.getText().toString().equals("")) {
                    showToast(getString(R.string.password_not_null));
                    return;
                }
                gotologin(etaccount.getText().toString(), etpassword.getText().toString());
            }
        });
    }

    private void gotologin(String username, String password) {
        Api.Login(username, password, new JsonCallBack<Result<Auth>>() {
            @Override
            public void onSuccess(Response<Result<Auth>> response) {
                Result<Auth> body = response.body();
                if (body.isSucess()) {
                    SharedPreferencesUtil.saveData(LoginActivity.this,"username",username);
                    SharedPreferencesUtil.saveData(LoginActivity.this,"password",password);
                    MyApplication.auth = body.getData();
                    if (MyApplication.cashierDO == null) {
                        getdeviceinfo(1);
                    } else {
                        if (casherModel == 1) {
                            //自助收银
                            startActivity(new Intent(LoginActivity.this, WelcomeActivity.class));
                        } else {
                            //人工收银
                            startActivity(new Intent(LoginActivity.this, ManualCasherActivity.class));
                        }
                        finish();
                    }
                } else {
                    showToast(body.getMsg());
                }

            }

            @Override
            public void onError(Response<Result<Auth>> response) {
                showToast("网络故障，请检查网络" + response.getException().getMessage());
            }
        });

    }
}
